<template>
    <div class="app-container">
        <div style="text-align: center;">
            <!-- 晋级流程图片 -->
             <img src="http://192.168.3.11:8086/image/technology/039c6a0121b243709efc72f6431218a2.png" height="200px">
         </div>
        <el-steps v-if="this.createForm.type == 22" :active="ferState" align-center>
          <el-step title="开始" description=""></el-step>
          <el-step title="晋级" description=""></el-step>
          <el-step title="岗位案例培训" description=""></el-step>
          <el-step title="考核" description=""></el-step>
          <el-step title="晋级通过" description=""></el-step>
          <el-step title="回写MES信息" description=""></el-step>
          <el-step title="结束" description=""></el-step>
        </el-steps>
        <el-steps v-if="this.createForm.type == 222" :active="ferState" align-center>
          <el-step title="开始" description=""></el-step>
          <el-step title="降级" description=""></el-step>
          <el-step title="岗位案例培训" description=""></el-step>
          <el-step title="考核" description=""></el-step>
          <el-step title="晋级通过" description=""></el-step>
          <el-step title="回写MES信息" description=""></el-step>
          <el-step title="结束" description=""></el-step>
        </el-steps>
        <div style="margin: 5px 0 5px 50px;display: flex;">
            <el-link style="font-size: 20px;margin-right: 10px;" :underline="false" target="_blank">基础信息</el-link>
            <!-- <el-button type="primary">批量导入</el-button>   -->
            <!-- <el-upload
            class="upload-demo"
            ref="upload"
            :action="action"
            :on-success="handleSuccess"
            :file-list="fileList"
            :headers="httpHeader"   
            :auto-upload="false"
            >
              <el-button slot="trigger" size="small" type="primary">批量导入</el-button>
              <div style="display: inline;">
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
              </div>
            </el-upload> -->
        </div>  
        <div>
            <el-form :inline="true" :model="createForm"  :rules="rules" ref="createForm">
                <div style="display: flex; ">
                    <el-form-item label="姓名" prop="userName" label-width="100px">
                        <el-input disabled v-model="createForm.userName" autosize  style="width: 120px"/>
                    </el-form-item>
                    <el-form-item label="工号" prop="jobNumber" label-width="100px" >
                        <el-input disabled v-model="createForm.jobNumber" autosize style="width: 120px"/>
                    </el-form-item>
                    <el-form-item label="部门" prop="workCenter" label-width="100px" >
                        <el-input disabled v-model="createForm.workCenter" autosize style="width: 120px"/>
                    </el-form-item>
                    <el-form-item label="岗位类别" prop="jobCategory" label-width="100px" >
                        <el-input disabled v-model="createForm.jobCategory" autosize style="width: 120px"/>
                    </el-form-item>
                    <el-form-item label="岗位名称" prop="jobTitle" label-width="120px" >
                        <el-input disabled v-model="createForm.jobTitle" autosize style="width: 120px"/>
                    </el-form-item>
                </div>
                <div style="display: flex;">
                    <el-form-item label="岗位级别" prop="rankOfPosition" label-width="100px" >
                        <el-select 
                             v-model="createForm.rankOfPosition" 
                             clearable      
                             filterable
                             disabled
                             style="width: 120px"
                             class="ul-item">
                             <el-option :value="item" :label="item" v-for="(item,index) in this.centerList" :key="index"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="直接主管" prop="parentName" label-width="100px" >
                        <el-input disabled v-model="createForm.parentName" autosize style="width: 120px"/>
                    </el-form-item>
                    <el-form-item label="培训类别" prop="trainingCategory" label-width="100px">
                        <el-input disabled v-model="createForm.trainingCategory" autosize style="width: 120px"/>
                    </el-form-item>
                    <el-form-item label="入职时间" prop="entryTime" label-width="100px" >
                        <el-input disabled v-model="createForm.entryTime" autosize style="width: 120px"/>
                    </el-form-item>
                    <el-form-item label="培训原因" prop="type" label-width="120px" >
                        <el-input disabled v-model="createForm.type == 22 ? '晋级' : createForm.type == 222 ? '降级' : ''" autosize style="width: 120px"/>
                    </el-form-item>
                </div>
            </el-form>
            <div>该岗位级别晋级/降级标准如下</div>
            <el-table :data="matchingList" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
                <el-table-column label=""  prop="title" align="center" width="100px"/>
                  <el-table-column label="岗位晋级标准" align="center" v-if="createForm.type == 22">
                    <el-table-column label="本岗位工作时长(≥月)"  prop="bePromotedEntryTimeStandard" align="center"  width="150px"/>
                    <el-table-column label="工作质量系数平均(本岗位工作时长)"  prop="bePromotedWorkingQualityFactor" align="center"  width="210px"/>
                    <el-table-column label="关键事项扣分≤"  prop="bePromotedPointsAreDeductedForCriticalMatters" align="center"  width="100px"/>
                  </el-table-column>
                  <el-table-column label="岗位降级标准" align="center" v-else-if="createForm.type == 222">
                    <el-table-column label="平均月份"  prop="demotionAverageMonth" align="center"  width="150px"/>
                    <el-table-column label="平均品质系数≤"  prop="demotionVerAgeQualityCoefficient" align="center"  width="210px"/>
                    <el-table-column label="关键事件扣分≥"  prop="demotionPointsAreDeductedForCriticalMatters" align="center"  width="100px"/>
                  </el-table-column>
                </el-table>

            <div style="display:flex;justify-content:space-between">
                <!-- pagination 分页 -->
                <div style="display: flex; justify-content: center; padding: 10px 0">
                  <span style="line-height: 28px; font-size: 13px"
                    >本次培训共 {{ total }} 人 </span>
                  <el-pagination
                    background
                    @current-change="handleCurrentChange"
                    :current-page="currentPage1"
                    :page-size="1"
                    layout="prev, pager, next"
                    small
                    :total="total"
                  >
                  </el-pagination>
                  <div>
                    <el-select clearable filterable v-model="tiemJobNumber" style="width: 120px">
                      <el-option :value="item.jobNumber" :label="item.userName" v-for="(item,index) in this.getUserList" :key="index"/>
                    </el-select>
                    <el-button type="primary" @click="searchName">搜索</el-button>
                </div>
                </div>
                <div  v-if="createForm" style="margin-right: 460px;">
                    <span style="margin-right: 20px">发起人：{{'MES系统'  }}</span>
                    <span>处理时间：{{createForm.updateTime ? createForm.updateTime:createForm.createTime}}</span>
                </div>
            </div>
        </div>
        <div>
            <div style="margin: 5px 0 5px 50px; display: flex; justify-content:space-between">
                <div>
                    <el-link style="font-size: 20px;margin-right: 10px;" :underline="false" target="_blank">岗位案例培训</el-link>
                    <el-button :disabled="boolGWAL" type="primary" @click="trainingClick">培训计划维护</el-button>      
                    <!-- <el-button type="primary" @click="trainingClick">培训计划维护</el-button>       -->
                </div>
                <el-button :disabled="ferState != 3" style="margin-right: 200px;" type="success"  size="medium" @click="skipTrain">完成培训</el-button>
            </div>
            <el-table :data="tableInfo" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
                <el-table-column  label="序号" type="index" align="center" width="80px"/>
                <el-table-column label="培训内容"  prop="trainingContent" align="center"/>
                <el-table-column label="内容类别"  prop="contentType" align="center"/>
                <el-table-column label="培训讲师"  prop="trainingInstructor" align="center"/>
                <el-table-column label="培训时间"  prop="trainingTime" align="center"/>
                <el-table-column label="考核方式"  prop="evaluationMode" align="center"/>
                <el-table-column label="培训记录"  prop="trainingPhoto" align="center">
                    <template slot-scope="scope" >  
                      <el-link style="font-size: 12px" :href="scope.row.trainingPhoto" target="_blank">{{scope.row.trainingPhoto}}</el-link>
                    </template>
                </el-table-column>
                <el-table-column label="考核记录"  prop="assessmentData" align="center">
                    <template slot-scope="scope" >  
                      <el-link style="font-size: 12px" :href="scope.row.assessmentData" target="_blank">{{scope.row.assessmentData}}</el-link>
                    </template>
                </el-table-column>
                <el-table-column label="效果评价"  prop="effectivenessEvaluation" align="center"/>
                <el-table-column label="培训结果"  prop="evaluationResult" align="center"/>
            </el-table> 
            <div v-if="tableInfo.length" style="display:flex;justify-content:space-between">
                <div></div>
                <div style="margin-right: 460px;">
                    <span style="margin-right: 20px">培训人：{{tableInfo[0].trainingInstructor }}</span>
                    <span>处理时间：{{tableInfo[0].updateTime ? tableInfo[0].updateTime:tableInfo[0].createTime}}</span>
                </div>
            </div>
        </div>

        <!-- 选择培训计划 -->
        <el-dialog title="选择培训计划" center :visible.sync="trainingShow" width="60%">
            <el-table :data="trainingList" element-loading-text="给我一首歌的时间" stripe border fit 
            highlight-current-row style="width: 100%;margin-top:15px;" :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center' }"
            default-expand-all
            @selection-change="SelectionChange2"
            @select="selectRow2">
                <el-table-column type="selection" width="70" align="center"></el-table-column>
                <!-- <el-table-column  label="序号" type="index" align="center" width="50px"/> -->
                <el-table-column label="培训内容"  prop="trainingContent" align="center" width="200"/>
                <el-table-column label="内容类别"  prop="contentType" align="center"/>
                <el-table-column label="导师/讲师"  prop="userName" align="center"/>
                <el-table-column label="培训类别"  prop="trainingCategory" align="center"/>
                <el-table-column label="培训岗位"  prop="trainingObjectsStr" align="center"/>
                <el-table-column label="考核方式"  prop="evaluationMode" align="center" width="200px"/>
            </el-table>
        <div slot="footer" class="dialog-footer">
            <el-button @click="trainingShow = false">取 消</el-button>
            <el-button type="primary" @click="trainingAffirm" :loading="printLoading">确 认</el-button>
        </div>
        </el-dialog>
        
    </div>
</template>

<script>
import { knowledgeFind,programFind,recordSaveList,recordFind,findByUser,getById } from "@/api/knowledgeSkill"
import { searchWorkers } from '@/api/chargingData'
import { findZplPrinterInfoList } from '../../api/orderAndMachine'
import {uploadURL} from '@/utils/baseURL'
import mixin from '@/utils/mixin.js'
import { set } from 'vue'
export default {
    name: 'promotedManagement',
    mixins: [mixin],
    data () {
        return {
            createForm:{
                userName:'',
                jobNumber:'',
                originalWorkCenter:'',
                originalJobCategory:'',
                originalJobTitle:'',
                originalUserName:'',
                originalParentNumber:'',
                nowWorkCenter:'',
                nowJobCategory:'',
                nowJobTitle:'',
                nowUserName:'',
                nowParentNumber:'',
            },
            rules: {
              userName: [
                { required: true, message: '姓名不能为空', trigger: 'blur' }
              ],
              jobNumber: [
                { required: true, message: '工号不能为空', trigger: 'blur' }
              ],
              originalWorkCenter: [
                { required: true, message: '原工作中心不能为空', trigger: 'blur' }
              ],
              originalJobCategory: [
                { required: true, message: '原岗位类别不能为空', trigger: 'blur' }
              ],
              originalJobTitle: [
                { required: true, message: '原岗位名称不能为空', trigger: 'blur' }
              ],
              originalUserName: [
                { required: true, message: '原直接主管不能为空', trigger: 'blur' }
              ],
              originalParentNumber: [
                { required: true, message: '原直接主管工号不能为空', trigger: 'blur' }
              ],
              nowWorkCenter: [
                { required: true, message: '新工作中心不能为空', trigger: 'blur' }
              ],
              nowJobCategory: [
                { required: true, message: '新岗位类别不能为空', trigger: 'blur' }
              ],
              nowJobTitle: [
                { required: true, message: '新岗位名称不能为空', trigger: 'blur' }
              ],
              nowUserName: [
                { required: true, message: '新直接主管不能为空', trigger: 'blur' }
              ],
              nowParentNumber: [
                { required: true, message: '新直接主管工号不能为空', trigger: 'blur' }
              ],
            },
            action: uploadURL + `/back/user-knowledge-record/UserKnowledgeRecordEntryExcel`,
            fileList: [],
            httpHeader: {
          'Authorization': ''
      },
            tiemJobNumber:'',
            userInfo:{},
            jobTitleList:[],
            tableInfo:[],           //岗前培训列表
            tableData:[],           //岗位培训列表
            currentPage1:0,
            total:0, 
            ferState:1,
            GQbool: true,
            GWbool: true,
            allBool: false,        // 全部禁用
            userList: [], 
            getUserList:[],            // 获取转岗人列表
            jobCategoryList: ['1线','1.5线','2线'], 
            dialogFormVisible: false,
            StartingList:[],       // 上岗人员列表
            startingName:'',
            printerName: '',
            printerNameList: [],
            rowSelect1:[],         // 选择列表
            printLoading: false,
            boolGWAL: true,
            showmatching: false,
            matchingList: [],
            trainingShow: false,    // 选择培训计划弹框
            trainingList:[],        // 培训计划列表
            rowSelect2:[],          // 培训计划选择列表
            trainingCategory: '',   // 培训类别
        }
    },
    computed: {
    },
    watch: {
      '$route'(to, from) {
        // 重置组件状态 
        this.handleFilter();
      }
    },
    methods: {
        selectRow2(selection, row) {
          console.log("单选", selection, row)
          this.rowSelect2 = selection;
        },
        SelectionChange2(select){
          console.log("全选",select)
          this.rowSelect2 = select;
        },
         // 名字搜索
         searchName(){
            // if(!this.tiemJobNumber) return this.$message.error('请选择员工!')
            this.handleFilter()
        },
        // 晋级降级规则
        async ruleClick(){
            this.matchingList = []
            this.matchingList.push({
                title: '岗位标准',
                bePromotedEntryTimeStandard: this.createForm.standardMonths,
                demotionAverageMonth: this.createForm.standardMonths,
                bePromotedWorkingQualityFactor: this.createForm.standardMassCoefficient,
                demotionVerAgeQualityCoefficient: this.createForm.standardMassCoefficient,
                bePromotedPointsAreDeductedForCriticalMatters: this.createForm.standardKeyDeductions,
                demotionPointsAreDeductedForCriticalMatters: this.createForm.standardKeyDeductions
            })
            let query = {title: '实际数据'}
            if(this.createForm.months != null){
                query.bePromotedEntryTimeStandard = this.createForm.months
                query.demotionAverageMonth = this.createForm.months
            }
            if(this.createForm.massCoefficient && this.createForm.massCoefficient != 0){
                query.bePromotedWorkingQualityFactor = this.createForm.massCoefficient
                query.demotionVerAgeQualityCoefficient = this.createForm.massCoefficient
            }
            if(this.createForm.keyDeductions != null){
                query.bePromotedPointsAreDeductedForCriticalMatters = this.createForm.keyDeductions
                query.demotionPointsAreDeductedForCriticalMatters = this.createForm.keyDeductions
            }
            
            this.matchingList.push(query)
            console.log(this.matchingList);
        },
        submitUpload() {
        //  this.httpHeader.Authorization = this.dealCookie(document.cookie)
         this.httpHeader.Authorization = this.$store.state.user.token,
         this.$refs.upload.submit()
         },
         // 上传成功
         handleSuccess(response){
          if(response.code == 1){
            this.fileList = []
            this.$message.success(response.msg)
          } else {
            this.$message.error(response.msg)
          }
            this.handleFilter()
        },
         // 获取个人信息
        async handleCurrentChange(e){
            console.log(e)
            this.GQbool = true
            this.GWbool = true
            this.tableInfo = []
            this.createForm = Object.assign({},this.getUserList[e-1])
            this.ferState = Number(this.getUserList[e-1].state)
            console.log(this.ferState)
                let query = {
                page: 1,
                limit: 10000,
                userName: this.createForm.userName,
                jobNumber: this.createForm.jobNumber,
                trainingCategory: '岗位案例培训',
                noState:'结束'
                }
                const res = await recordFind(query)
                this.tableInfo = res.data.list
                if(this.hasMoreThanThreeObjectsWithKeyFailing(this.tableInfo, 'evaluationResult','不合格')){
                    this.tableInfo = res.data.list
                }else if(this.ferState >= 3){
                    this.tableInfo = res.data.list
                }else if(this.ferState == 2){
                    this.boolGWAL = true
                    this.tableInfo = []
                }
                this.ruleClick()
        },
        // 点击岗位前完成培训
        skipTrain(){
            let query = {
                type: '晋级',
                name: this.createForm.userName,
            }
            const souceType =  this.createForm.type == 22 ? '晋级培训' : this.createForm.type == 222 ? '降级培训' : ''
            if(!this.tableInfo.length) return this.$message.error('没有培训计划列表！')
            query.trainingCategory = this.entryList[0].trainingCategory
            query.souceType = souceType
            this.$router.push({ path: '/knowledgeSkill/trainingResults', query: query})
        },
        setNowTime() {
            let date = new Date()
            // 获取年、月、日、时、分、秒  
            const year = date.getFullYear();  
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的  
            const day = String(date.getDate()).padStart(2, '0');  
            const hour = String(date.getHours()).padStart(2, '0');  
            const minute = String(date.getMinutes()).padStart(2, '0');  
            const second = String(date.getSeconds()).padStart(2, '0');  
            return `${year}-${month}-${day} ${hour}:${minute}:${second}`;   
        },
        // 点击培训按钮
        async trainingClick(){
            let query = {
                page:1,
                limit:10000,
                userKnowledgePostId: this.createForm.userKnowledgePostId, 
                trainingCategory: '岗位案例培训'
            }
            const res = await programFind(query)
            if(!res.data.list.length) return this.$message.error('没有培训计划列表！')
            this.trainingList = res.data.list
            this.trainingShow = true
        },
        // 选择培训计划点击确定
        async trainingAffirm(){
            this.ferState = 3
            let objectMap = []
            this.rowSelect2.forEach(item =>{
                objectMap.push({
                    userName: this.createForm.userName, 
                    jobNumber: this.createForm.jobNumber,
                    workCenter: this.createForm.workCenter,
                    jobCategory: this.createForm.jobCategory,
                    jobTitle: this.createForm.jobTitle,
                    userKnowledgePostId:this.createForm.userKnowledgePostId,
                    trainingContent: item.trainingContent,    
                    trainingInstructor:item.userName,
                    trainingCategory:item.trainingCategory,
                    evaluationMode:item.evaluationMode,
                    trainingTime:this.setNowTime(),
                    contentType:item.contentType,
                    souceType: this.createForm.type == 22 ? '晋级培训' : this.createForm.type == 222 ? '降级培训' :'',
                    userKnowledgeTrainingProgramId: item.id,  // 培训计划id
                    type:2,  // 1.入职与培训2.晋级管理3.转岗管理4.关键工序管理
                    state:3,
                })
                // await recordSave(query1)
            })
            // 批量添加 员工履历
            const res = await recordSaveList({objectMap:objectMap})
            if(res.code == 500) return
            if(res.code != '1') return this.$message.error(res.msg)
            this.trainingShow = false
            setTimeout(async () =>{
                let query = {
                    page:1,
                    limit:10000,
                    userName:this.createForm.userName,
                    jobNumber:this.createForm.jobNumber,
                    trainingCategory: '岗位案例培训',
                    noState:'结束'
                }
                const res = await recordFind(query)
                this.tableInfo = res.data.list
            },500)
            // 状态缓存
            this.getUserList.forEach((item,index) =>{
                if(item.id == this.createForm.id){
                    this.$set(this.getUserList[index],'state',this.ferState)
                }
            })
        },
         // 获取岗位
        async getjobTitle(){
            let query = {page:1,  limit:10000}
            if(this.createForm.nowJobCategory){query.jobCategory = this.createForm.nowJobCategory}
            if(this.createForm.nowWorkCenter){query.workCenter = this.createForm.nowWorkCenter}
            const res = await knowledgeFind(query)
            this.jobTitleList = res.data.list
            if(!res.data.list.length) return this.$message.error('工作中心和岗位类别未查询到数据!')
    },
        async getData(){
            if(!this.createForm.userName || !this.createForm.jobNumber) return this.$message.error('请填写姓名或工号!')
            let query ={
                page: 1,
                limit: 10,
                status:1,
                userName: this.createForm.userName,
                jobNumber: this.createForm.jobNumber
            }
            const res = await searchWorkers(query)
            // if(!res.data.records.lenght) return  
            this.userInfo = res.data.records[0]
            this.$set(this.createForm, 'originalWorkCenter', this.userInfo.departmentName)
            this.$set(this.createForm, 'originalParentNumber', this.userInfo.parentNumber)
            this.$set(this.createForm, 'originalUserName', this.userInfo.parentName)
            this.$set(this.createForm, 'originalJobCategory', this.userInfo.userKnowledgePost.jobCategory)
            this.$set(this.createForm, 'originalJobTitle', this.userInfo.userKnowledgePost.jobTitle)
            this.$set(this.createForm, 'originalUserKnowledgePostId', this.userInfo.userKnowledgePost.id)
        },
        async handleFilter(){
            let query = {
                // page:1,
                // limit:10000,
                type:'2,22,222',
                noState:'结束',
                jobNumber: this.tiemJobNumber 
            }
            const res = await findByUser(query)
            console.log('res',res)
            this.getUserList = res.data.list
            this.total = this.getUserList.length
            if(this.getUserList.length){
              this.createForm = Object.assign({},this.getUserList[0])
              this.ferState = Number(this.getUserList[0].state)
              console.log(this.ferState)
                let query = {
                page: 1,
                limit: 10000,
                userName: this.createForm.userName,
                jobNumber: this.createForm.jobNumber,
                trainingCategory: '岗位案例培训',
                noState:'结束'
                }
                const res = await recordFind(query)
                this.tableInfo = res.data.list
                if(this.hasMoreThanThreeObjectsWithKeyFailing(this.tableInfo, 'evaluationResult','不合格')){
                    this.tableInfo = res.data.list
                }else if(this.ferState >= 3){
                    this.tableInfo = res.data.list
                }else if(this.ferState == 2){
                    this.boolGWAL = true
                    this.tableInfo = []
                }
                this.ruleClick()
            }
        },
        hasMoreThanThreeObjectsWithKeyFailing(arr, key, passingValue) {  
            let failingCount = 0; // 用于计数不合格的对象数量  
            // 遍历数组中的每个对象  
            for (let i = 0; i < arr.length; i++) {  
                // 检查当前对象是否具有指定的键  
                if (arr[i].hasOwnProperty(key)) {  
                    // 如果该键的值不等于给定的合格值，则增加不合格计数  
                    if (arr[i][key] !== passingValue) {  
                        failingCount++;  
                        // 如果不合格的对象数量已经超过三条，则直接返回false
                        if (failingCount > 3) {  
                            return false;  
                        }  
                    }  
                }  
            }
            // 如果没有超过三条不合格的对象，则返回true  
            return failingCount < 3;  
        },
    },
    // 进入页面获取table信息
    mounted() {
        this.handleFilter()
    }
}
</script>

<style lang="scss" scoped>
.app-container{
    margin: 10px;
}
/deep/ .el-table__header .el-table-column--selection .cell .el-checkbox:after {
  content: "全选";
  margin-left: 5px;
}
</style>
